home *** CD-ROM | disk | FTP | other *** search
/ Sprite 1984 - 1993 / Sprite 1984 - 1993.iso / src / cmds / bash-1.12 / dist / jobs.c < prev    next >
Encoding:
C/C++ Source or Header  |  1992-01-17  |  53.7 KB  |  2,290 lines

  1. /* The thing that makes children, remembers them, and contains wait loops. */
  2.  
  3. /* This file works with both POSIX and BSD systems. */
  4.  
  5. /* Copyright (C) 1989 Free Software Foundation, Inc.
  6.  
  7. This file is part of GNU Bash, the Bourne Again SHell.
  8.  
  9. Bash is free software; you can redistribute it and/or modify it under
  10. the terms of the GNU General Public License as published by the Free
  11. Software Foundation; either version 1, or (at your option) any later
  12. version.
  13.  
  14. Bash is distributed in the hope that it will be useful, but WITHOUT ANY
  15. WARRANTY; without even the implied warranty of MERCHANTABILITY or
  16. FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  17. for more details.
  18.  
  19. You should have received a copy of the GNU General Public License along
  20. with Bash; see the file COPYING.  If not, write to the Free Software
  21. Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
  22.  
  23. /* Something that can be ignored. */
  24. #define IGNORE_ARG (char *)0
  25.  
  26. #include "config.h"
  27.  
  28. #if !defined (JOB_CONTROL)
  29. #include "nojobs.c"
  30. #else /* JOB_CONTROL */
  31.  
  32. #include <sys/types.h>
  33. #include "trap.h"
  34. #include <stdio.h>
  35. #include <signal.h>
  36. #include <errno.h>
  37.  
  38. #if !defined (USG) || defined (HAVE_RESOURCE)
  39. #include <sys/time.h>
  40. #endif /* USG */
  41.  
  42. #if !defined (_POSIX_VERSION)
  43. #  if defined (HAVE_RESOURCE)
  44. #    include <sys/resource.h>
  45. #  endif
  46. #endif /* _POSIX_VERSION */
  47.  
  48. #include <sys/file.h>
  49. #include <sys/ioctl.h>
  50. #include <sys/param.h>
  51. #include "filecntl.h"
  52.  
  53. /* Terminal handling stuff, to save and restore tty state. */
  54. #define NEW_TTY_DRIVER
  55.  
  56. /* Define this if your output is getting swallowed.  It's a no-op on
  57.    machines with the termio or termios tty drivers. */
  58. /* #define DRAIN_OUTPUT */
  59.  
  60. #if defined (_POSIX_VERSION) && !defined (TERMIOS_MISSING)
  61. #  undef NEW_TTY_DRIVER
  62. #  define TERMIOS_TTY_DRIVER
  63. #  if defined (sun)
  64. #    define _POSIX_SOURCE
  65. #  endif
  66. #else /* !_POSIX_VERSION */
  67. #  if defined (USG) || defined (hpux) || defined (Xenix) || defined (sgi)
  68. #    undef NEW_TTY_DRIVER
  69. #    define TERMIO_TTY_DRIVER
  70. #  endif /* USG | hpux | Xenix | sgi */
  71. #endif /* !_POSIX_VERSION */
  72.  
  73. /* Include the right header file for the specific type of terminal
  74.    handler installed on this system. */
  75. #if defined (NEW_TTY_DRIVER)
  76. #include <sgtty.h>
  77. #endif
  78.  
  79. #if defined (TERMIO_TTY_DRIVER)
  80. #include <termio.h>
  81. #endif
  82.  
  83. #if defined (TERMIOS_TTY_DRIVER)
  84. /* For Sun workstations we undefine a couple of defines so that
  85.    the inclusion of termios.h won't cause complaints. */
  86. #  if defined (sun)
  87. #    undef ECHO
  88. #    undef NOFLSH
  89. #    undef TOSTOP
  90. #  endif /* sun */
  91. #  include <termios.h>
  92. #endif /* TERMIOS_TTY_DRIVER */
  93.  
  94. /* For the TIOCGPGRP and TIOCSPGRP ioctl parameters on HP-UX */
  95.  
  96. #if defined (hpux) && !defined (TERMIOS_TTY_DRIVER)
  97. #include <bsdtty.h>
  98. #endif /* hpux && !TERMIOS_TTY_DRIVER */
  99.  
  100. #include "shell.h"
  101. #include "jobs.h"
  102.  
  103. /* Not all systems define errno in errno.h. */
  104. extern int errno;
  105. extern int interactive, asynchronous_notification;
  106. extern char *shell_name;
  107. extern char *sys_siglist[];
  108.  
  109. /* The array of known jobs. */
  110. JOB **jobs = (JOB **)NULL;
  111.  
  112. /* The number of slots currently allocated to JOBS. */
  113. int job_slots = 0;
  114.  
  115. /* The number of additional slots to allocate when we run out. */
  116. #define JOB_SLOTS 5
  117.  
  118. /* The controlling tty for this shell. */
  119. int shell_tty = -1;
  120.  
  121. /* The shell's process group. */
  122. pid_t shell_pgrp = NO_PID;
  123.  
  124. /* The terminal's process group. */
  125. pid_t terminal_pgrp = NO_PID;
  126.  
  127. /* The process group of the shell's parent. */
  128. pid_t original_pgrp = NO_PID;
  129.  
  130. /* The process group of the pipeline currently being made. */
  131. pid_t pipeline_pgrp = (pid_t)0;
  132.  
  133. #if defined (PGRP_PIPE)
  134. /* Pipes which each shell uses to communicate with the process group leader
  135.    until all of the processes in a pipeline have been started.  Then the
  136.    process leader is allowed to continue. */
  137. int pgrp_pipe[2] = { -1, -1 };
  138. #endif
  139.       
  140. /* The job which is current; i.e. the one that `%+' stands for. */
  141. int current_job = NO_JOB;
  142.  
  143. /* The previous job; i.e. the one that `%-' stands for. */
  144. int previous_job = NO_JOB;
  145.  
  146. /* Last child made by the shell.  */
  147. pid_t last_made_pid = NO_PID;
  148.  
  149. /* Pid of the last asynchronous child. */
  150. pid_t last_asynchronous_pid = NO_PID;
  151.  
  152. /* The pipeline currently being built. */
  153. PROCESS *the_pipeline = (PROCESS *)NULL;
  154.  
  155. /* If this is non-zero, do job control. */
  156. int job_control = 1;
  157.  
  158. /* Call this when you start making children. */
  159. int already_making_children = 0;
  160.  
  161. /* Functions local to this file. */
  162. static sighandler flush_child ();
  163. static PROCESS *find_pipeline ();
  164. static char *job_working_directory ();
  165. static pid_t last_pid ();
  166. static int set_new_line_discipline (), map_over_jobs (), last_running_job ();
  167. static int most_recent_job_in_state (), last_stopped_job (), find_job ();
  168. static void notify_of_job_status (), cleanup_dead_jobs (), discard_pipeline ();
  169. static void add_process (), set_current_job (), reset_current ();
  170. static void pretty_print_job ();
  171. #if defined (PGRP_PIPE)
  172. static void pipe_read (), pipe_close ();
  173. #endif
  174.  
  175. #if !defined (_POSIX_VERSION)
  176.  
  177. /* These are definitions to map POSIX 1003.1 functions onto existing BSD
  178.    library functions and system calls. */
  179. #define setpgid(pid, pgrp)    setpgrp (pid, pgrp)
  180. #define tcsetpgrp(fd, pgrp)    ioctl ((fd), TIOCSPGRP, &(pgrp))
  181.  
  182. pid_t
  183. tcgetpgrp (fd)
  184.      int fd;
  185. {
  186.   pid_t pgrp;
  187.  
  188.   /* ioctl will handle setting errno correctly. */
  189.   if (ioctl (fd, TIOCGPGRP, &pgrp) < 0)
  190.     return (-1);
  191.   return (pgrp);
  192. }
  193.  
  194. /* Perform OPERATION on NEWSET, perhaps leaving information in OLDSET. */
  195. sigprocmask (operation, newset, oldset)
  196.      int operation, *newset, *oldset;
  197. {
  198.   switch (operation)
  199.     {
  200.     case SIG_BLOCK:
  201.       *oldset = sigblock (*newset);
  202.       break;
  203.  
  204.     case SIG_SETMASK:
  205.       sigsetmask (*newset);
  206.       break;
  207.  
  208.     default:
  209.       report_error ("Bad code in jobs.c: sigprocmask");
  210.     }
  211. }
  212. #endif /* !_POSIX_VERSION */
  213.  
  214. /* Return the working directory for the current process. */
  215. static char *
  216. job_working_directory ()
  217. {
  218.   extern char *get_working_directory ();
  219.   char *dir;
  220.  
  221.   dir = get_string_value ("PWD");
  222.   if (dir)
  223.     return (savestring (dir));
  224.  
  225.   dir = get_working_directory ("");
  226.   if (dir)
  227.     return (dir);
  228.  
  229.   return (savestring ("<unknown>"));
  230. }
  231.  
  232. making_children ()
  233. {
  234.   if (already_making_children)
  235.     return;
  236.  
  237.   already_making_children = 1;
  238.   start_pipeline ();
  239. }
  240.  
  241. stop_making_children ()
  242. {
  243.   already_making_children = 0;
  244. }
  245.  
  246. /* Start building a pipeline.  */
  247. start_pipeline ()
  248. {
  249.   if (the_pipeline)
  250.     {
  251.       discard_pipeline (the_pipeline);
  252.       the_pipeline = (PROCESS *)NULL;
  253.       pipeline_pgrp = 0;
  254. #if defined (PGRP_PIPE)
  255.       pipe_close (pgrp_pipe);
  256. #endif
  257.     }
  258.  
  259. #if defined (PGRP_PIPE)
  260.   if (job_control)
  261.     {
  262.       if (pipe (pgrp_pipe) == -1)
  263.     report_error ("start_pipeline: pgrp pipe");
  264.     }
  265. #endif
  266. }
  267.  
  268. /* Stop building a pipeline.  Install the process list in the job array.
  269.    This returns the index of the newly installed job.
  270.    DEFERRED is a command structure to be executed upon satisfactory
  271.    execution exit of this pipeline. */
  272. int
  273. stop_pipeline (async, deferred)
  274.      int async;
  275.      COMMAND *deferred;
  276. {
  277.   register int i, j;
  278.   JOB *newjob = (JOB *)NULL;
  279.   char *get_string_value ();
  280.   sigset_t set, oset;
  281.  
  282.   BLOCK_CHILD (set, oset);
  283.  
  284. #if defined (PGRP_PIPE)
  285.   /* The parent closes the process group synchronization pipe. */
  286.   pipe_close (pgrp_pipe);
  287. #endif
  288.     
  289.   cleanup_dead_jobs ();
  290.  
  291.   if (!job_slots)
  292.     {
  293.       jobs =
  294.     (JOB **)xmalloc ((job_slots = JOB_SLOTS) * sizeof (JOB *));
  295.  
  296.       /* Now blank out these new entries. */
  297.       for (i = 0; i < job_slots; i++)
  298.     jobs[i] = (JOB *)NULL;
  299.     }
  300.  
  301.   /* Scan from the last slot backward, looking for the next free one. */
  302.   for (i = job_slots; i; i--)
  303.     if (jobs[i - 1])
  304.       break;
  305.  
  306.   /* Do we need more room? */
  307.   if (i == job_slots)
  308.     {
  309.       jobs = (JOB **)realloc
  310.     (jobs, (1 + (job_slots += JOB_SLOTS)) * sizeof (JOB *));
  311.  
  312.       for (j = i; j < job_slots; j++)
  313.     jobs[j] = (JOB *)NULL;
  314.     }
  315.  
  316.   /* Add the current pipeline to the job list. */
  317.   if (the_pipeline)
  318.     {
  319.       register PROCESS *p;
  320.  
  321.       newjob = (JOB *)xmalloc (sizeof (JOB));
  322.  
  323.       for (p = the_pipeline; p->next != the_pipeline; p = p->next);
  324.       p->next = (PROCESS *)NULL;
  325.       newjob->pipe = (PROCESS *)reverse_list (the_pipeline);
  326.       for (p = newjob->pipe; p->next; p = p->next);
  327.       p->next = newjob->pipe;
  328.  
  329.       the_pipeline = (PROCESS *)NULL;
  330.       newjob->pgrp = pipeline_pgrp;
  331.       pipeline_pgrp = 0;
  332.  
  333.       /* Flag to see if in another pgrp. */
  334.       newjob->job_control = job_control;
  335.  
  336.       /* Set the state of this pipeline. */
  337.       {
  338.     register PROCESS *p = newjob->pipe;
  339.     register int any_alive = 0;
  340.     register int any_stopped = 0;
  341.  
  342.     do
  343.       {
  344.         any_alive |= p->running;
  345.         any_stopped |= WIFSTOPPED (p->status);
  346.         p = p->next;
  347.       }
  348.     while (p != newjob->pipe);
  349.  
  350.     if (any_alive)
  351.       {
  352.         newjob->state = JRUNNING;
  353.       }
  354.     else
  355.       {
  356.         if (any_stopped)
  357.           newjob->state = JSTOPPED;
  358.         else
  359.           newjob->state = JDEAD;
  360.       }
  361.       }
  362.  
  363.       newjob->notified = 0;
  364.       newjob->wd = job_working_directory ();
  365.       newjob->deferred = deferred;
  366.  
  367.       jobs[i] = newjob;
  368.     }
  369.  
  370.   if (async)
  371.     {
  372.       if (newjob)
  373.     newjob->foreground = 0;
  374.       reset_current ();
  375.     }
  376.   else
  377.     {
  378.       if (newjob)
  379.     {
  380.       newjob->foreground = 1;
  381.       /*
  382.        *        !!!!! NOTE !!!!!  (chet@ins.cwru.edu)
  383.        *
  384.        * The currently-accepted job control wisdom says to set the
  385.        * terminal's process group n+1 times in an n-step pipeline:
  386.        * once in the parent and once in each child.  This is where
  387.        * the parent gives it away.
  388.        *
  389.        */
  390.       if (job_control && newjob->pgrp)
  391.         give_terminal_to (newjob->pgrp);
  392.     }
  393.     }
  394.  
  395.   stop_making_children ();
  396.   UNBLOCK_CHILD (oset);
  397.   return (current_job);
  398. }
  399.  
  400. /* Delete all DEAD jobs that the user had received notification about. */
  401. static void
  402. cleanup_dead_jobs ()
  403. {
  404.   register int i;
  405.   sigset_t set, oset;
  406.  
  407.   BLOCK_CHILD (set, oset);
  408.  
  409.   for (i = 0; i < job_slots; i++)
  410.     if (jobs[i] && JOBSTATE (i) == JDEAD && jobs[i]->notified)
  411.       delete_job (i);
  412.  
  413.   UNBLOCK_CHILD (oset);
  414. }
  415.  
  416. /* Delete the job at INDEX from the job list. */
  417. delete_job (index)
  418.      int index;
  419. {
  420.   register JOB *temp = jobs[index];
  421.  
  422.   if (index == current_job || index == previous_job)
  423.     reset_current ();
  424.  
  425.   jobs[index] = (JOB *)NULL;
  426.  
  427.   free (temp->wd);
  428.   discard_pipeline (temp->pipe);
  429.  
  430.   if (temp->deferred)
  431.     dispose_command (temp->deferred);
  432.  
  433.   free (temp);
  434. }
  435.  
  436. /* Get rid of the data structure associated with a process chain. */
  437. static void
  438. discard_pipeline (chain)
  439.      register PROCESS *chain;
  440. {
  441.   register PROCESS *this, *next;
  442.  
  443.   this = chain;
  444.   do
  445.     {
  446.       next = this->next;
  447.       if (this->command)
  448.     free (this->command);
  449.       free (this);
  450.       this = next;
  451.     }
  452.   while (this != chain);
  453. }
  454.  
  455. /* Add this process to the chain being built in the_pipeline.
  456.    NAME is the command string that will be exec'ed later.
  457.    PID is the process id of the child. */
  458. static void
  459. add_process (name, pid)
  460.      char *name;
  461.      pid_t pid;
  462. {
  463.   PROCESS *t = (PROCESS *)xmalloc (sizeof (PROCESS));
  464.  
  465.   t->next = the_pipeline;
  466.   t->pid = pid;
  467.   WSTATUS (t->status) = 0;
  468.   t->running = 1;
  469.   t->command = name;
  470.   the_pipeline = t;
  471.  
  472.   if (!(t->next))
  473.     t->next = t;
  474.   else
  475.     {
  476.       register PROCESS *p = t->next;
  477.  
  478.       while (p->next != t->next) p = p->next;
  479.       p->next = t;
  480.     }
  481. }
  482.  
  483. /* Map FUNC over the list of jobs.  If FUNC returns non-zero,
  484.    then it is time to stop mapping, and that is the return value
  485.    for map_over_jobs.  FUNC is called with a JOB, arg1, arg2,
  486.    and INDEX. */
  487. static int
  488. map_over_jobs (func, arg1, arg2)
  489.      Function *func;
  490. {
  491.   register int i;
  492.  
  493.   for (i = 0; i < job_slots; i++)
  494.     {
  495.       if (jobs[i])
  496.     {
  497.       int result = (*func)(jobs[i], arg1, arg2, i);
  498.       if (result)
  499.         return (result);
  500.     }
  501.     }
  502.   return (0);
  503. }
  504.  
  505. /* Cause all the jobs in the current pipeline to exit. */
  506. terminate_current_pipeline ()
  507. {
  508.   if (pipeline_pgrp && pipeline_pgrp != shell_pgrp)
  509.     {
  510.       killpg (pipeline_pgrp, SIGTERM);
  511.       killpg (pipeline_pgrp, SIGCONT);
  512.     }
  513. }
  514.  
  515. /* Cause all stopped jobs to exit. */
  516. void
  517. terminate_stopped_jobs ()
  518. {
  519.   register int i;
  520.  
  521.   for (i = 0; i < job_slots; i++)
  522.     {
  523.       if (jobs[i] && (JOBSTATE (i) == JSTOPPED))
  524.     {
  525.       killpg (jobs[i]->pgrp, SIGTERM);
  526.       killpg (jobs[i]->pgrp, SIGCONT);
  527.     }
  528.     }
  529. }
  530.  
  531. /* Cause all jobs, running or stopped, to receive a hangup signal. */
  532. void
  533. hangup_all_jobs ()
  534. {
  535.   register int i;
  536.  
  537.   for (i = 0; i < job_slots; i++)
  538.     {
  539.       if (jobs[i])
  540.     {
  541.       killpg (jobs[i]->pgrp, SIGHUP);
  542.       if (JOBSTATE (i) == JSTOPPED)
  543.         killpg (jobs[i]->pgrp, SIGCONT);
  544.     }
  545.     }
  546. }
  547.  
  548. kill_current_pipeline ()
  549. {
  550.   stop_making_children ();
  551.   start_pipeline ();
  552. }
  553.  
  554. /* Return the pipeline that PID belongs to.  Note that the pipeline
  555.    doesn't have to belong to a job. */
  556. static PROCESS *
  557. find_pipeline (pid)
  558.      pid_t pid;
  559. {
  560.   int job;
  561.  
  562.   /* See if this process is in the pipeline that we are building. */
  563.   if (the_pipeline)
  564.     {
  565.       register PROCESS *p = the_pipeline;
  566.  
  567.       do
  568.     {
  569.       /* Return it if we found it. */
  570.       if (p->pid == pid)
  571.         return (p);
  572.  
  573.       p = p->next;
  574.     }
  575.       while (p != the_pipeline);
  576.     }
  577.  
  578.   job = find_job (pid);
  579.  
  580.   if (job == NO_JOB)
  581.     return ((PROCESS *)NULL);
  582.   else
  583.     return (jobs[job]->pipe);
  584. }
  585.  
  586. /* Return the job index that PID belongs to, or NO_JOB if it doesn't
  587.    belong to any job. */
  588. static int
  589. find_job (pid)
  590.      pid_t pid;
  591. {
  592.   register int i;
  593.   register PROCESS *p;
  594.  
  595.   for (i = 0; i < job_slots; i++)
  596.     {
  597.       if (jobs[i])
  598.     {
  599.       p = jobs[i]->pipe;
  600.  
  601.       do
  602.         {
  603.           if (p->pid == pid)
  604.         return (i);
  605.  
  606.           p = p->next;
  607.         }
  608.       while (p != jobs[i]->pipe);
  609.     }
  610.     }
  611.  
  612.   return (NO_JOB);
  613. }
  614.  
  615. /* Print descriptive information about the job with leader pid PID. */
  616. describe_pid (pid)
  617.      pid_t pid;
  618. {
  619.   int job;
  620.   sigset_t set, oset;
  621.  
  622.   BLOCK_CHILD (set, oset);
  623.  
  624.   job = find_job (pid);
  625.  
  626.   if (job != NO_JOB)
  627.     printf ("[%d] %d\n", job + 1, pid);
  628.   else
  629.     programming_error ("describe_pid: No such pid (%d)!\n", pid);
  630.  
  631.   UNBLOCK_CHILD (oset);
  632. }
  633.  
  634. /* This is the way to print out information on a job if you
  635.    know the index.  FORMAT is:
  636.  
  637.     JLIST_NORMAL)   [1]+ Running       emacs
  638.     JLIST_LONG  )   [1]+ 2378 Running      emacs
  639.     -1      )   [1]+ 2378          emacs
  640.  
  641.     JLIST_NORMAL)   [1]+ Stopped       ls | more
  642.     JLIST_LONG  )   [1]+ 2369 Stopped      ls
  643.              2367        | more
  644.     JLIST_PID_ONLY)
  645.     Just list the pid of the process group leader (really
  646.     the process group).
  647.     JLIST_CHANGED_ONLY)
  648.     Use format JLIST_NORMAL, but list only jobs about which
  649.     the user has not been notified. */
  650. static void
  651. pretty_print_job (index, format, stream)
  652.      int index, format;
  653.      FILE *stream;
  654. {
  655.   register PROCESS *p, *first, *last;
  656.   int name_padding;
  657.   char retcode_name_buffer[20];
  658.   sigset_t set, oset;
  659.  
  660.   BLOCK_CHILD (set, oset);
  661.  
  662.   /* Format only pid information about the process group leader? */
  663.   if (format == JLIST_PID_ONLY)
  664.     {
  665.       fprintf (stream, "%d\n", jobs[index]->pipe->pid);
  666.       UNBLOCK_CHILD (oset);
  667.       return;
  668.     }
  669.  
  670.   if (format == JLIST_CHANGED_ONLY)
  671.     {
  672.       if (jobs[index]->notified == 1)
  673.     {
  674.       UNBLOCK_CHILD (oset);
  675.       return;
  676.     }
  677.       format = JLIST_STANDARD;
  678.     }
  679.  
  680.   fprintf (stream, "[%d]%c ", index + 1,
  681.        (index == current_job) ? '+':
  682.        (index == previous_job) ? '-' : ' ');
  683.  
  684.   first = last = p = jobs[index]->pipe;
  685.   while (last->next != first)
  686.     last = last->next;
  687.  
  688.   /* We have printed information about this job.  When the job's
  689.      status changes, flush_child () sets the notification flag to 0. */
  690.   jobs[index]->notified = 1;
  691.  
  692.   for (;;)
  693.     {
  694.       if (p != first)
  695.     fprintf (stream, format ? "     " : " |");
  696.  
  697.       if (format)
  698.     fprintf (stream, "%d", p->pid);
  699.  
  700.       fprintf (stream, " ");
  701.  
  702.       if (format > -1)
  703.     {
  704.       PROCESS *show = format ? p : last;
  705.       char *temp = "Done";
  706.  
  707.       if (JOBSTATE (index) == JSTOPPED && !format)
  708.         temp = "Stopped";
  709.  
  710.       if (JOBSTATE (index) == JRUNNING)
  711.         temp = "Running";
  712.       else
  713.         {
  714.         if (WIFSTOPPED (show->status))
  715.           temp = sys_siglist[WSTOPSIG (show->status)];
  716.         else if (WIFSIGNALED (show->status))
  717.           temp = sys_siglist[WTERMSIG (show->status)];
  718.         else if (WIFEXITED (show->status))
  719.           {
  720.             temp = retcode_name_buffer;
  721.             sprintf (temp, "Exit %d", WEXITSTATUS (show->status));
  722.           }
  723.         else
  724.           temp = "Unknown status";
  725.         }
  726.  
  727.       if (p != first)
  728.         {
  729.           if (format)
  730.         {
  731.           if (show->running == first->running &&
  732.               WSTATUS (show->status) == WSTATUS (first->status))
  733.             temp = "";
  734.         }
  735.           else
  736.         temp = (char *)NULL;
  737.         }
  738.  
  739.       if (temp)
  740.         {
  741.           fprintf (stream, "%s", temp);
  742.  
  743.           if (strlen (temp))
  744.         name_padding = LONGEST_SIGNAL_DESC - strlen (temp);
  745.           else
  746.         name_padding = LONGEST_SIGNAL_DESC - 2; /* strlen ("| ") */
  747.  
  748.           fprintf (stream, "%*s", name_padding, "");
  749.  
  750.           if ((!WIFSTOPPED (show->status)) && (WIFCORED (show->status)))
  751.         fprintf (stream, "(core dumped) ");
  752.         }
  753.     }
  754.  
  755.       if (p != first && format)
  756.     fprintf (stream, "| ");
  757.  
  758.       fprintf (stream, "%s", p->command);
  759.  
  760.       if (p == last) 
  761.     {
  762.       char *wd = job_working_directory ();
  763.  
  764.       if (JOBSTATE (index) == JRUNNING && jobs[index]->foreground == 0)
  765.         fprintf (stream, " &");
  766.  
  767.       if (strcmp (wd, jobs[index]->wd) != 0)
  768.         fprintf (stream,
  769.              "  (wd: %s)", polite_directory_format (jobs[index]->wd));
  770.       free (wd);
  771.     }
  772.  
  773.       if (format || (p == last))
  774.     fprintf (stream, "\r\n");
  775.  
  776.       if (p == last)
  777.     break;
  778.       p = p->next;
  779.     }
  780.  
  781.   fflush (stream);
  782.   UNBLOCK_CHILD (oset);
  783. }
  784.  
  785. int
  786. list_one_job (job, format, ignore, index)
  787.      JOB *job;
  788.      int format, ignore, index;
  789. {
  790.   pretty_print_job (index, format, stdout);
  791.   return (0);
  792. }
  793.  
  794. /* List jobs.  If FORMAT is non-zero, then the long form of the information
  795.    is printed, else just a short version. */
  796. list_jobs (format)
  797.      int format;
  798. {
  799.   cleanup_dead_jobs ();
  800.   map_over_jobs (list_one_job, format, (int)IGNORE_ARG);
  801. }
  802.  
  803. /* Fork, handling errors.  Returns the pid of the newly made child, or 0.
  804.    COMMAND is just for remembering the name of the command; we don't do
  805.    anything else with it.  ASYNC_P says what to do with the tty.  If
  806.    non-zero, then don't give it away. */
  807. pid_t
  808. make_child (command, async_p)
  809.      char *command;
  810.      int async_p;
  811. {
  812.   sigset_t set, oset;
  813.   pid_t pid;
  814.  
  815.   sigemptyset (&set);
  816.   sigaddset (&set, SIGCHLD);
  817.   sigaddset (&set, SIGINT);
  818.   sigemptyset (&oset);
  819.   sigprocmask (SIG_BLOCK, &set, &oset);
  820.  
  821.   making_children ();
  822.  
  823.   /* Make new environment array if neccessary. */
  824.   maybe_make_export_env ();
  825.  
  826.   /* Create the child, handle severe errors. */
  827.   if ((pid = fork ()) < 0)
  828.     {
  829.       report_error ("fork: %s", (char *)strerror (errno));
  830.  
  831.       /* Kill all of the processes in the current pipeline. */
  832.       terminate_current_pipeline ();
  833.  
  834.       /* Discard the current pipeline, if any. */
  835.       if (the_pipeline)
  836.     kill_current_pipeline ();
  837.  
  838.       throw_to_top_level ();    /* Reset signals, etc. */
  839.     }
  840.  
  841.   if (!pid)
  842.     {
  843.       /* In the child.  Give this child the right process group, set the
  844.      signals to the default state for a new process. */
  845.       extern sigset_t top_level_mask;
  846.  
  847.       pid_t mine = getpid ();
  848.  
  849.       /* Cancel traps, in trap.c. */
  850.       restore_original_signals ();
  851.  
  852.       /* Restore top-level signal mask. */
  853.       sigprocmask (SIG_SETMASK, &top_level_mask, (sigset_t *)NULL);
  854.  
  855.       if (job_control)
  856.     {
  857.       /* All processes in this pipeline belong in the same
  858.          process group. */
  859.  
  860.       if (!pipeline_pgrp)    /* Then this is the first child. */
  861.         pipeline_pgrp = mine;
  862.  
  863.       /* Check for running command in backquotes. */
  864.       if (pipeline_pgrp == shell_pgrp)
  865.         {
  866.           signal (SIGTSTP, SIG_IGN);
  867.           signal (SIGTTOU, SIG_IGN);
  868.           signal (SIGTTIN, SIG_IGN);
  869.         }
  870.       else
  871.         {
  872.           signal (SIGTSTP, SIG_DFL);
  873.           signal (SIGTTOU, SIG_DFL);
  874.           signal (SIGTTIN, SIG_DFL);
  875.         }
  876.  
  877.       /* Set the process group before trying to mess with the terminal's
  878.          process group.  This is mandated by POSIX. */
  879.       /* This is in accordance with the Posix 1003.1 standard,
  880.          section B.7.2.4, which says that trying to set the terminal
  881.          process group with tcsetpgrp() to an unused pgrp value (like
  882.          this would have for the first child) is an error.  Section
  883.          B.4.3.3, p. 237 also covers this, in the context of job control
  884.          shells. */
  885.       if (setpgid (mine, pipeline_pgrp) < 0)
  886.         fprintf (stderr, "%s: child setpgid (%d to %d) error %d: %s\n",
  887.              shell_name, mine, pipeline_pgrp, errno,
  888.              (char *)strerror (errno));
  889. #if defined (PGRP_PIPE)
  890.       if (pipeline_pgrp == mine)
  891.         {
  892. #endif
  893.           if (!async_p)
  894.         give_terminal_to (pipeline_pgrp);
  895.  
  896. #if defined (PGRP_PIPE)
  897.           pipe_read (pgrp_pipe);
  898.         }
  899. #endif
  900.     }
  901.       else            /* Without job control... */
  902.     {
  903.       if (!pipeline_pgrp)
  904.         pipeline_pgrp = shell_pgrp;
  905.  
  906.       /* If these signals are set to SIG_DFL, we encounter the curious
  907.          situation of an interactive ^Z to a running process *working*
  908.          and stopping the process, but being unable to do anything with
  909.          that process to change its state.  On the other hand, if they
  910.          are set to SIG_IGN, jobs started from scripts do not stop when
  911.          the shell running the script gets a SIGTSTP and stops. */
  912.  
  913.       signal (SIGTSTP, SIG_DFL);
  914.       signal (SIGTTOU, SIG_DFL);
  915.       signal (SIGTTIN, SIG_DFL);
  916.  
  917.       if (async_p)
  918.         {
  919.           signal (SIGINT, SIG_IGN);
  920.           signal (SIGQUIT, SIG_IGN);
  921.         }
  922.     }
  923.  
  924. #if defined (PGRP_PIPE)
  925.       /* Release the process group pipe, since our call to setpgid ()
  926.      is done.  The last call to pipe_close is done in stop_pipeline. */
  927.       pipe_close (pgrp_pipe);
  928. #endif /* PGRP_PIPE */
  929.  
  930.       if (async_p)
  931.     last_asynchronous_pid = getpid ();
  932.     }
  933.   else
  934.     {
  935.       /* In the parent.  Remember the pid of the child just created
  936.      as the proper pgrp if this is the first child. */
  937.  
  938.       if (job_control)
  939.     {
  940.       if (!pipeline_pgrp)
  941.         {
  942.           pipeline_pgrp = pid;
  943.           /* Don't twiddle terminal pgrps in the parent!  This is the bug,
  944.          not the good thing of twiddling them in the child! */
  945.           /* give_terminal_to (pipeline_pgrp); */
  946.         }
  947.       /* This is done on the recommendation of the Rationale section of
  948.          the POSIX 1003.1 standard, where it discusses job control and
  949.          shells.  It is done to avoid possible race conditions. (Ref.
  950.          1003.1 Rationale, section B.4.3.3, page 236). */
  951.       setpgid (pid, pipeline_pgrp);
  952.     }
  953.       else
  954.     {
  955.       if (!pipeline_pgrp)
  956.         pipeline_pgrp = shell_pgrp;
  957.     }
  958.  
  959.       /* Place all processes into the jobs array regardless of the
  960.      state of job_control. */
  961.       add_process (command, pid);
  962.  
  963.       if (async_p)
  964.     last_asynchronous_pid = pid;
  965.  
  966.       last_made_pid = pid;
  967.  
  968.       /* Unblock SIGINT and SIGCHLD. */
  969.       sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
  970.     }
  971.  
  972.   return (pid);
  973. }
  974.  
  975. /* When we end a job abnormally, or if we stop a job, we set the tty to the
  976.    state kept in here.  When a job ends normally, we set the state in here
  977.    to the state of the tty. */
  978.  
  979. #if defined (NEW_TTY_DRIVER)
  980. static struct sgttyb shell_tty_info;
  981. static struct tchars shell_tchars;
  982. static struct ltchars shell_ltchars;
  983. #endif /* NEW_TTY_DRIVER */
  984.  
  985. #if defined (TERMIO_TTY_DRIVER)
  986. static struct termio shell_tty_info;
  987. #endif /* TERMIO_TTY_DRIVER */
  988.  
  989. #if defined (TERMIOS_TTY_DRIVER)
  990. static struct termios shell_tty_info;
  991. #endif /* TERMIOS_TTY_DRIVER */
  992.  
  993. #if defined (NEW_TTY_DRIVER) && defined (DRAIN_OUTPUT)
  994. /* Since the BSD tty driver does not allow us to change the tty modes
  995.    while simultaneously waiting for output to drain and preserving
  996.    typeahead, we have to drain the output ourselves before calling
  997.    ioctl.  We cheat by finding the length of the output queue, and
  998.    using select to wait for an appropriate length of time.  This is
  999.    a hack, and should be labeled as such (it's a hastily-adapted
  1000.    mutation of a `usleep' implementation).  It's only reason for
  1001.    existing is the flaw in the BSD tty driver. */
  1002.  
  1003. static int ttspeeds[] =
  1004. {
  1005.   0, 50, 75, 110, 134, 150, 200, 300, 600, 1200,
  1006.   1800, 2400, 4800, 9600, 19200, 38400
  1007. };
  1008.  
  1009. static void
  1010. draino (fd, ospeed)
  1011.      int fd, ospeed;
  1012. {
  1013.   register int delay = ttspeeds[ospeed];
  1014.   int n;
  1015.  
  1016.   if (!delay)
  1017.     return;
  1018.  
  1019.   while ((ioctl (fd, TIOCOUTQ, &n) == 0) && n)
  1020.     {
  1021.       if (n > (delay / 100))
  1022.     {
  1023.       struct timeval tv;
  1024.  
  1025.       n *= 10;        /* 2 bits more for conservativeness. */
  1026.       tv.tv_sec = n / delay;
  1027.       tv.tv_usec = ((n % delay) * 1000000) / delay;
  1028.       select (fd, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv);
  1029.     }
  1030.       else
  1031.     break;
  1032.     }
  1033. }
  1034. #endif /* NEW_TTY_DRIVER && DRAIN_OUTPUT */
  1035.  
  1036. /* Return the fd from which we are actually getting input.  Should be
  1037.    inlined by the compiler. */
  1038. static int
  1039. input_tty ()
  1040. {
  1041.   int tty = shell_tty;
  1042.  
  1043.   if (tty == -1)
  1044.     tty = fileno (stdin);
  1045.  
  1046.   return (tty);
  1047. }
  1048.  
  1049. /* Fill the contents of shell_tty_info with the current tty info. */
  1050. get_tty_state ()
  1051. {
  1052.   int tty = input_tty ();
  1053.  
  1054.   if (tty != -1)
  1055.     {
  1056. #if defined (NEW_TTY_DRIVER)
  1057.       ioctl (tty, TIOCGETP, &shell_tty_info);
  1058.       ioctl (tty, TIOCGETC, &shell_tchars);
  1059.       ioctl (tty, TIOCGLTC, &shell_ltchars);
  1060. #endif /* NEW_TTY_DRIVER */
  1061.  
  1062. #if defined (TERMIO_TTY_DRIVER)
  1063.       ioctl (tty, TCGETA, &shell_tty_info);
  1064. #endif /* TERMIO_TTY_DRIVER */
  1065.  
  1066. #if defined (TERMIOS_TTY_DRIVER)
  1067.       if (tcgetattr (tty, &shell_tty_info) < 0)
  1068.     {
  1069.       extern int shell_level;
  1070.  
  1071.       fprintf (stderr, "%s: [%d: %d] tcgetattr: %s\n", shell_name,
  1072.            getpid (), shell_level, (char *)strerror (errno));
  1073.     }
  1074. #endif /* TERMIOS_TTY_DRIVER */
  1075.     }
  1076. }
  1077.  
  1078. /* Make the current tty use the state in shell_tty_info. */
  1079. set_tty_state ()
  1080. {
  1081.   int tty = input_tty ();
  1082.  
  1083.   if (tty != -1)
  1084.     {
  1085. #if defined (NEW_TTY_DRIVER)
  1086. #  if defined (DRAIN_OUTPUT)
  1087.       draino (tty, shell_tty_info.sg_ospeed);
  1088. #  endif /* DRAIN_OUTPUT */
  1089.       ioctl (tty, TIOCSETN, &shell_tty_info);
  1090.       ioctl (tty, TIOCSETC, &shell_tchars);
  1091.       ioctl (tty, TIOCSLTC, &shell_ltchars);
  1092. #endif /* NEW_TTY_DRIVER */
  1093.  
  1094. #if defined (TERMIO_TTY_DRIVER)
  1095.       ioctl (tty, TCSETAW, &shell_tty_info);
  1096. #endif /* TERMIO_TTY_DRIVER */
  1097.  
  1098. #if defined (TERMIOS_TTY_DRIVER)
  1099.       if (tcsetattr (tty, TCSADRAIN, &shell_tty_info) < 0)
  1100.     {
  1101.       extern int shell_level;
  1102.  
  1103.       fprintf (stderr, "%s: [%d: %d] tcsetattr: %s\n", shell_name,
  1104.            getpid (), shell_level, (char *)strerror (errno));
  1105.     }
  1106. #endif /* TERMIOS_TTY_DRIVER */
  1107.     }
  1108. }
  1109.  
  1110. /* Given an index into the jobs array JOB, return the pid of the last
  1111.    process in that job's pipeline.  This is the one whose exit status
  1112.    counts. */
  1113. static pid_t
  1114. last_pid (job)
  1115.      int job;
  1116. {
  1117.   register PROCESS *p;
  1118.   sigset_t set, oset;
  1119.  
  1120.   BLOCK_CHILD (set, oset);
  1121.  
  1122.   p = jobs[job]->pipe;
  1123.   while (p->next != jobs[job]->pipe)
  1124.     p = p->next;
  1125.  
  1126.   UNBLOCK_CHILD (oset);
  1127.   return (p->pid);
  1128. }
  1129.  
  1130. /* Wait for a particular child of the shell to finish executing.
  1131.    This low-level function prints an error message if PID is not
  1132.    a child of this shell.  It returns -1 if it fails, or 0 if not. */
  1133. int
  1134. wait_for_single_pid (pid)
  1135.      pid_t pid;
  1136. {
  1137.   register PROCESS *child;
  1138.  
  1139.   child = find_pipeline (pid);
  1140.  
  1141.   if (!child)
  1142.     {
  1143.       report_error ("wait: pid %d is not a child of this shell", pid);
  1144.       return (127);
  1145.     }
  1146.  
  1147.   return (wait_for (pid));
  1148. }
  1149.  
  1150. /* Wait for all of the backgrounds of this shell to finish. */
  1151. void
  1152. wait_for_background_pids ()
  1153. {
  1154.   while (1)
  1155.     {
  1156.       register int i, count = 0;
  1157.       sigset_t set, oset;
  1158.  
  1159.       BLOCK_CHILD (set, oset);
  1160.  
  1161.       for (i = 0; i < job_slots; i++)
  1162.     if (jobs[i] && (JOBSTATE (i) == JRUNNING) && !(jobs[i]->foreground))
  1163.       {
  1164.         count++;
  1165.         break;
  1166.       }
  1167.  
  1168.       if (!count)
  1169.     {
  1170.       UNBLOCK_CHILD (oset);
  1171.       break;
  1172.     }
  1173.  
  1174.       for (i = 0; i < job_slots; i++)
  1175.     if (jobs[i] && (JOBSTATE (i) == JRUNNING) && !jobs[i]->foreground)
  1176.       {
  1177.         pid_t pid = last_pid (i);
  1178.         UNBLOCK_CHILD (oset);
  1179.         QUIT;
  1180.         wait_for_single_pid (pid);
  1181.         break;
  1182.       }
  1183.     }
  1184. }
  1185.  
  1186. /* Wait for pid (one of our children) to terminate, then
  1187.    return the termination state. */
  1188. int
  1189. wait_for (pid)
  1190.      pid_t pid;
  1191. {
  1192.   extern int last_command_exit_value;
  1193.   int job, termination_state;
  1194.   register PROCESS *child;
  1195.   sigset_t set, oset;
  1196.   
  1197.   BLOCK_CHILD (set, oset);
  1198.   termination_state = last_command_exit_value;
  1199.  
  1200.   /* If we say wait_for (), then we have a record of this child somewhere.
  1201.      If this child and all of its peers are not running, then don't
  1202.      sigpause (), since there is no need to. */
  1203.  wait_loop:
  1204.  
  1205.   /* If the shell is running interactively, and the shell is the foreground
  1206.      process (e.g. executing a `wait' command) then let the user C-c out. */
  1207.   if (interactive && (terminal_pgrp == shell_pgrp))
  1208.     QUIT;
  1209.  
  1210.   child = find_pipeline (pid);
  1211.  
  1212.   if (!child)
  1213.     {
  1214.       give_terminal_to (shell_pgrp);
  1215.       UNBLOCK_CHILD (oset);
  1216.       programming_error ("wait_for: No record of pid %d", pid);
  1217.     }
  1218.  
  1219.   /* If this child is part of a job, then we are really waiting for the
  1220.      job to finish.  Otherwise, we are waiting for the child to finish. */
  1221.  
  1222.   job = find_job (pid);
  1223.  
  1224.   if (job != NO_JOB)
  1225.     {
  1226.       register int job_state = 0, any_stopped = 0;
  1227.       register PROCESS *p = jobs[job]->pipe;
  1228.  
  1229.       do
  1230.     {
  1231.       job_state |= p->running;
  1232.       if (!p->running)
  1233.         any_stopped |= WIFSTOPPED (p->status);
  1234.       p = p->next;
  1235.     }
  1236.       while (p != jobs[job]->pipe);
  1237.  
  1238.       if (job_state == 0)
  1239.     {
  1240.       if (any_stopped)
  1241.         jobs[job]->state = JSTOPPED;
  1242.       else
  1243.         jobs[job]->state = JDEAD;
  1244.     }
  1245.     }
  1246.  
  1247.   if (child->running ||
  1248.       ((job != NO_JOB) && (JOBSTATE (job) == JRUNNING)))
  1249.     {
  1250. #if !defined (SCO)
  1251.       sigset_t set;
  1252.  
  1253.       sigemptyset (&set);
  1254.       sigsuspend (&set);
  1255. #else /* SCO Unix */
  1256.       struct sigaction act, oact;
  1257.  
  1258.       act.sa_handler = SIG_DFL;
  1259.       sigemptyset (&act.sa_mask);
  1260.       act.sa_flags = 0;
  1261.  
  1262.       sigaction (SIGCHLD, &act, &oact);
  1263.       flush_child (0);
  1264.       sigaction (SIGCHLD, &oact, (struct sigaction *)NULL);
  1265. #endif /* !SCO */
  1266.  
  1267.       goto wait_loop;
  1268.     }
  1269.  
  1270.   /* The exit state of the command is either the termination state of the
  1271.      child, or the termination state of the job.  If a job, the status
  1272.      of the last child in the pipeline is the significant one. */
  1273.  
  1274.   if (job != NO_JOB)
  1275.     {
  1276.       register PROCESS *p = jobs[job]->pipe;
  1277.  
  1278.       while (p->next != jobs[job]->pipe)
  1279.     p = p->next;
  1280.       if (WIFSIGNALED (p->status))
  1281.     termination_state = 128 + WTERMSIG (p->status);
  1282.       else if (!WIFSTOPPED (p->status))
  1283.     termination_state = WEXITSTATUS (p->status);
  1284.     }
  1285.   else
  1286.     {
  1287.       if (WIFSIGNALED (child->status))
  1288.     termination_state = 128 + WTERMSIG (child->status);
  1289.       else if (!WIFSTOPPED (child->status))
  1290.     termination_state = WEXITSTATUS (child->status);
  1291.     }
  1292.  
  1293.   if (job == NO_JOB || jobs[job]->job_control)
  1294.     give_terminal_to (shell_pgrp);
  1295.  
  1296.   /* If the command did not exit cleanly, or the job is just
  1297.      being stopped, then reset the tty state back to what it
  1298.      was before this command.  Do this only if the shell is
  1299.      interactive. */
  1300.   if (job != NO_JOB && interactive)
  1301.     {
  1302.       if (WIFSIGNALED (child->status) || WIFSTOPPED (child->status))
  1303.     set_tty_state ();
  1304.       else
  1305.     get_tty_state ();
  1306.  
  1307.       notify_and_cleanup ();
  1308.     }
  1309.  
  1310.  wait_exit:
  1311.   UNBLOCK_CHILD (oset);
  1312.   return (termination_state);
  1313. }
  1314.  
  1315. /* Wait for the last process in the pipeline for JOB. */
  1316. int
  1317. wait_for_job (job)
  1318.      int job;
  1319. {
  1320.   pid_t pid = last_pid (job);
  1321.   return (wait_for (pid));
  1322. }
  1323.  
  1324. /* Print info about dead jobs, and then delete them from the list
  1325.    of known jobs. */
  1326. notify_and_cleanup ()
  1327. {
  1328.   if (interactive)
  1329.     notify_of_job_status ();
  1330.   cleanup_dead_jobs ();
  1331. }
  1332.  
  1333. /* Return the next closest (chronologically) job to JOB which is in
  1334.    STATE.  STATE can be JSTOPPED, JRUNNING.  NO_JOB is returned if
  1335.    there is no next recent job. */
  1336. static int
  1337. most_recent_job_in_state (job, state)
  1338.      int job;
  1339.      JOB_STATE state;
  1340. {
  1341.   register int i;
  1342.   sigset_t set, oset;
  1343.  
  1344.   BLOCK_CHILD (set, oset);
  1345.  
  1346.   for (i = job - 1; i >= 0; i--)
  1347.     {
  1348.       if (jobs[i])
  1349.     {
  1350.       if (JOBSTATE (i) == state)
  1351.         {
  1352.           /* Found it! */
  1353.           UNBLOCK_CHILD (oset);
  1354.           return (i);
  1355.         }
  1356.     }
  1357.     }
  1358.   UNBLOCK_CHILD (oset);
  1359.   return (NO_JOB);
  1360. }
  1361.  
  1362. /* Return the newest *stopped* job older than JOB, or NO_JOB if not
  1363.    found. */
  1364. static int
  1365. last_stopped_job (job)
  1366.      int job;
  1367. {
  1368.   return (most_recent_job_in_state (job, JSTOPPED));
  1369. }
  1370.  
  1371. /* Return the newest *running* job older than JOB, or NO_JOB if not
  1372.    found. */
  1373. static int
  1374. last_running_job (job)
  1375.      int job;
  1376. {
  1377.   return (most_recent_job_in_state (job, JRUNNING));
  1378. }
  1379.  
  1380. /* Make JOB be the current job, and make previous be useful. */
  1381. static void
  1382. set_current_job (job)
  1383.      int job;
  1384. {
  1385.   int candidate = NO_JOB;
  1386.  
  1387.   if (current_job != job)
  1388.     {
  1389.       previous_job = current_job;
  1390.       current_job = job;
  1391.     }
  1392.  
  1393.   /* First choice for previous_job is the old current_job. */
  1394.   if (previous_job != current_job &&
  1395.       previous_job != NO_JOB &&
  1396.       jobs[previous_job] &&
  1397.       JOBSTATE (previous_job) == JSTOPPED)
  1398.     return;
  1399.  
  1400.   /* Second choice:  Newest stopped job that is older than
  1401.      the current job. */
  1402.   if (JOBSTATE (current_job) == JSTOPPED)
  1403.     {
  1404.       candidate = last_stopped_job (current_job);
  1405.  
  1406.       if (candidate != NO_JOB)
  1407.     {
  1408.       previous_job = candidate;
  1409.       return;
  1410.     }
  1411.     }
  1412.  
  1413.   /* If we get here, there is either only one stopped job, in which case it is
  1414.      the current job and the previous job should be set to the newest running
  1415.      job, or there are only running jobs and the previous job should be set to
  1416.      the newest running job older than the current job.  We decide on which
  1417.      alternative to use based on whether or not JOBSTATE(current_job) is
  1418.      JSTOPPED. */
  1419.  
  1420.   if (JOBSTATE (current_job) == JRUNNING)
  1421.     candidate = last_running_job (current_job);
  1422.   else
  1423.     candidate = last_running_job (job_slots);
  1424.  
  1425.   if (candidate != NO_JOB)
  1426.     {
  1427.       previous_job = candidate;
  1428.       return;
  1429.     }
  1430.  
  1431.   /* There is only a single job, and it is both `+' and `-'. */
  1432.   previous_job = current_job;
  1433. }
  1434.  
  1435. /* Make current_job be something useful, if it isn't already. */
  1436.  
  1437. /* Here's the deal:  The newest non-running job should be `+', and the
  1438.    next-newest non-running job should be `-'.  If there is only a single
  1439.    stopped job, the previous_job is the newest non-running job.  If there
  1440.    are only running jobs, the newest running job is `+' and the
  1441.    next-newest running job is `-'. */
  1442. static void
  1443. reset_current ()
  1444. {
  1445.   int candidate = NO_JOB;
  1446.  
  1447.   if (current_job != NO_JOB &&
  1448.       job_slots && jobs[current_job] &&
  1449.       JOBSTATE (current_job) == JSTOPPED)
  1450.     {
  1451.       candidate = current_job;
  1452.     }
  1453.   else
  1454.     {
  1455.       /* First choice: the previous job! */
  1456.       if (previous_job != NO_JOB && jobs[previous_job] &&
  1457.       JOBSTATE (previous_job) == JSTOPPED)
  1458.     candidate = previous_job;
  1459.  
  1460.       /* Second choice: the most recently stopped job. */
  1461.       if (candidate == NO_JOB)
  1462.     candidate = last_stopped_job (job_slots);
  1463.  
  1464.       if (candidate == NO_JOB)
  1465.     {
  1466.       /* Third choice: the newest running job. */
  1467.       candidate = last_running_job (job_slots);
  1468.     }
  1469.     }
  1470.  
  1471.   /* If we found a job to use, then use it.  Otherwise, there
  1472.      are no jobs period. */
  1473.   if (candidate != NO_JOB)
  1474.     set_current_job (candidate);
  1475.   else
  1476.     current_job = previous_job = NO_JOB;
  1477. }
  1478.  
  1479. /* Start a job.  FOREGROUND if non-zero says to do that.  Otherwise,
  1480.    start the job in the background.  JOB is a zero-based index into
  1481.    JOBS.  Returns -1 if it is unable to start a job, and the return
  1482.    status of the job otherwise. */
  1483. int
  1484. start_job (job, foreground)
  1485.      int job, foreground;
  1486. {
  1487.   register PROCESS *p;
  1488.   int already_running;
  1489.   sigset_t set, oset;
  1490.   char *wd;
  1491. #if defined (NEW_TTY_DRIVER)
  1492.   static struct sgttyb save_stty;
  1493. #endif
  1494.  
  1495. #if defined (TERMIO_TTY_DRIVER)
  1496.   static struct termio save_stty;
  1497. #endif
  1498.  
  1499. #if defined (TERMIOS_TTY_DRIVER)
  1500.   static struct termios save_stty;
  1501. #endif
  1502.  
  1503.   BLOCK_CHILD (set, oset);
  1504.   already_running = (JOBSTATE (job) == JRUNNING);
  1505.  
  1506.   if (!foreground && already_running)
  1507.     {
  1508.       extern char *this_command_name;
  1509.  
  1510.       report_error ("%s: bg background job?", this_command_name);
  1511.       UNBLOCK_CHILD (oset);
  1512.       return (-1);
  1513.     }
  1514.  
  1515.   wd = job_working_directory ();
  1516.  
  1517.   /* You don't know about the state of this job.  Do you? */
  1518.   jobs[job]->notified = 0;
  1519.  
  1520.   if (foreground)
  1521.     {
  1522.       set_current_job (job);
  1523.       jobs[job]->foreground = 1;
  1524.     }
  1525.  
  1526.   /* Tell the outside world what we're doing. */
  1527.   p = jobs[job]->pipe;
  1528.  
  1529.   if (!foreground)
  1530.     fprintf (stderr, "[%d]%c ", job + 1,
  1531.        (job == current_job) ? '+': ((job == previous_job) ? '-' : ' '));
  1532.  
  1533.   do
  1534.     {
  1535.       fprintf (stderr, "%s%s",
  1536.            p->command, p->next != jobs[job]->pipe? " | " : "");
  1537.       p = p->next;
  1538.     }
  1539.   while (p != jobs[job]->pipe);
  1540.  
  1541.   if (!foreground)
  1542.     fprintf (stderr, " &");
  1543.  
  1544.   if (strcmp (wd, jobs[job]->wd) != 0)
  1545.     fprintf (stderr, "    (wd: %s)", polite_directory_format (jobs[job]->wd));
  1546.  
  1547.   fprintf (stderr, "\n");
  1548.  
  1549.   free (wd);
  1550.  
  1551.   /* Run the job. */
  1552.   if (!already_running)
  1553.     {
  1554.       /* Each member of the pipeline is now running. */
  1555.       p = jobs[job]->pipe;
  1556.  
  1557.       do
  1558.     {
  1559.       if (WIFSTOPPED (p->status))
  1560.         p->running = 1;
  1561.       p = p->next;
  1562.     }
  1563.       while (p != jobs[job]->pipe);
  1564.  
  1565.       /* This means that the job is running. */
  1566.       JOBSTATE (job) = JRUNNING;
  1567.     }
  1568.  
  1569.   /* Save the tty settings before we start the job in the foreground. */
  1570.   if (foreground)
  1571.     {
  1572.       get_tty_state ();
  1573.       save_stty = shell_tty_info;
  1574.     }
  1575.  
  1576.   /* Give the terminal to this job. */
  1577.   if (foreground)
  1578.     {
  1579.       if (jobs[job]->job_control)
  1580.     give_terminal_to (jobs[job]->pgrp);
  1581.     }
  1582.   else
  1583.     jobs[job]->foreground = 0;
  1584.  
  1585.   /* If the job is already running, then don't bother jump-starting it. */
  1586.   if (!already_running)
  1587.     {
  1588.       jobs[job]->notified = 1;
  1589.       killpg (jobs[job]->pgrp, SIGCONT);
  1590.     }
  1591.  
  1592.   UNBLOCK_CHILD (oset);
  1593.  
  1594.   if (foreground)
  1595.     {
  1596.       pid_t pid = last_pid (job);
  1597.       int s = wait_for (pid);
  1598.  
  1599.       shell_tty_info = save_stty;
  1600.       set_tty_state ();
  1601.       return (s);
  1602.     }
  1603.   else
  1604.     {
  1605.       reset_current ();
  1606.       return (0);
  1607.     }
  1608. }
  1609.  
  1610. /* Give PID SIGNAL.  This determines what job the pid belongs to (if any).
  1611.    If PID does belong to a job, and the job is stopped, then CONTinue the
  1612.    job after giving it SIGNAL.  Returns -1 on failure.  If GROUP is non-null,
  1613.    then kill the process group associated with PID. */
  1614. int
  1615. kill_pid (pid, signal, group)
  1616.      pid_t pid;
  1617.      int signal, group;
  1618. {
  1619.   register PROCESS *p;
  1620.   int job, result = EXECUTION_SUCCESS;
  1621.   sigset_t set, oset;
  1622.  
  1623.   BLOCK_CHILD (set, oset);
  1624.   p = find_pipeline (pid);
  1625.   job = find_job (pid);
  1626.  
  1627.   if (group)
  1628.     {
  1629.       if (job != NO_JOB)
  1630.     {
  1631.       jobs[job]->notified = 0;
  1632.  
  1633.       /* Kill process in backquotes or one started without job control? */
  1634.       if (jobs[job]->pgrp == shell_pgrp)
  1635.         {
  1636.           p = jobs[job]->pipe;
  1637.  
  1638.           do
  1639.         {
  1640.           kill (p->pid, signal);
  1641.           if (!p->running && (signal == SIGTERM || signal == SIGHUP))
  1642.             kill (p->pid, SIGCONT);
  1643.           p = p->next;
  1644.         } while (p != jobs[job]->pipe);
  1645.         }
  1646.       else
  1647.         {
  1648.           result = killpg (jobs[job]->pgrp, signal);
  1649.           if (p && (JOBSTATE (job) == JSTOPPED) &&
  1650.           (signal == SIGTERM || signal == SIGHUP))
  1651.         killpg (jobs[job]->pgrp, SIGCONT);
  1652.         }
  1653.     }
  1654.       else
  1655.     {
  1656.       result = killpg (pid, signal);
  1657.     }
  1658.     }
  1659.   else
  1660.     {
  1661.       result = kill (pid, signal);
  1662.     }
  1663.   UNBLOCK_CHILD (oset);
  1664.   return (result);
  1665. }
  1666.  
  1667. /* Take care of system dependencies that must be handled when waiting for
  1668.    children.  The arguments to the WAITPID macro match those to the Posix.1
  1669.    waitpid() function. */
  1670.  
  1671. #if defined (Ultrix) && defined (mips) && defined (_POSIX_VERSION)
  1672. #  define WAITPID(pid, statusp, options) \
  1673.     wait3 ((union wait *)statusp, options, (struct rusage *)0)
  1674. #else
  1675. #  if defined (_POSIX_VERSION)
  1676. #    define WAITPID(pid, statusp, options) \
  1677.     waitpid ((pid_t)pid, statusp, options)
  1678. #  else
  1679. #    if defined (hpux)
  1680. #      define WAITPID(pid, statusp, options) \
  1681.     wait3 (statusp, options, (int *)0)
  1682. #    else
  1683. #      define WAITPID(pid, statusp, options) \
  1684.     wait3 (statusp, options, (struct rusage *)0)
  1685. #    endif /* !hpux */
  1686. #  endif /* !_POSIX_VERSION */
  1687. #endif /* !(Ultrix && mips && _POSIX_VERSION) */
  1688.  
  1689. /* If the system needs it, REINSTALL_SIGCHLD_HANDLER will reinstall the
  1690.    handler for SIGCHLD. */
  1691.  
  1692. #if defined (hpux) && !defined (_POSIX_VERSION)
  1693. #  define REINSTALL_SIGCHLD_HANDLER signal (SIGCHLD, flush_child)
  1694. #else
  1695. #  define REINSTALL_SIGCHLD_HANDLER
  1696. #endif /* !hpux || _POSIX_VERSION */
  1697.  
  1698. /* Flush_child () flushes at least one of the children that we are waiting for.
  1699.    It gets run when we have gotten a SIGCHLD signal, and stops when there
  1700.    aren't any children terminating any more.  If SIG is 0, this is to be a
  1701.    blocking wait for a single child.  It is here to get around SCO Unix's
  1702.    broken sigsuspend (). */
  1703.  
  1704. static sighandler
  1705. flush_child (sig)
  1706.      int sig;
  1707. {
  1708.   WAIT status;
  1709.   PROCESS *child;
  1710.   pid_t pid;
  1711.   int call_set_current = 0, last_stopped_job = NO_JOB;
  1712.   int children_exited = 0;
  1713.  
  1714.   do
  1715.     {
  1716.       pid = WAITPID (-1, &status, sig ? (WNOHANG | WUNTRACED) : WUNTRACED);
  1717.  
  1718.       if (pid > 0)
  1719.     {
  1720.       REINSTALL_SIGCHLD_HANDLER;
  1721.  
  1722.       /* Locate our PROCESS for this pid. */
  1723.       child = find_pipeline (pid);
  1724.  
  1725.       /* It is not an error to have a child terminate that we did
  1726.          not have a record of.  This child could have been part of
  1727.          a pipeline in backquote substitution. */
  1728.       if (child)
  1729.         {
  1730.           int job = find_job (pid);
  1731.  
  1732.           while (child->pid != pid)
  1733.         child = child->next;
  1734.  
  1735.           /* Remember status, and fact that process is not running. */
  1736.           child->status = status;
  1737.           child->running = 0;
  1738.  
  1739.           if (job != NO_JOB)
  1740.         {
  1741.           int job_state = 0;
  1742.           int any_stopped = 0;
  1743.  
  1744.           child = jobs[job]->pipe;
  1745.           jobs[job]->notified = 0;
  1746.  
  1747.           /* If all children are not running, but any of them is
  1748.              stopped, then the job is stopped, not dead. */
  1749.           do
  1750.            {
  1751.               job_state |= child->running;
  1752.               if (!child->running)
  1753.             any_stopped |= (WIFSTOPPED (child->status));
  1754.               child = child->next;
  1755.             }
  1756.           while (child != jobs[job]->pipe);
  1757.  
  1758.           if (job_state == 0)
  1759.             {
  1760.               if (any_stopped)
  1761.             {
  1762.               jobs[job]->state = JSTOPPED;
  1763.               jobs[job]->foreground = 0;
  1764.               call_set_current++;
  1765.               last_stopped_job = job;
  1766.             }
  1767.               else
  1768.             {
  1769.               jobs[job]->state = JDEAD;
  1770.  
  1771.               if (job == last_stopped_job)
  1772.                 last_stopped_job = NO_JOB;
  1773.  
  1774.               /* If this job was not started with job control,
  1775.                  then the shell has already seen the SIGINT, since
  1776.                  the process groups are the same.  In that case,
  1777.                  don't send the SIGINT to the shell; it will
  1778.                  surprise people to have a stray interrupt
  1779.                  arriving some time after they killed the job. */
  1780.  
  1781.               /* XXX - should the `|| interactive' be there? */
  1782.               if (jobs[job]->foreground &&
  1783.                   (jobs[job]->job_control || interactive) &&
  1784.                   WTERMSIG (jobs[job]->pipe->status) == SIGINT)
  1785.                 kill (getpid (), SIGINT);
  1786.             }
  1787.             }
  1788.         }
  1789.         }
  1790.       /* If we have caught a child, and a trap was set for SIGCHLD, then
  1791.          bump up the count of the number of children that have exited,
  1792.          so we know how many times to call it. */
  1793.       children_exited++;
  1794.     }
  1795.     }
  1796. #if defined (SCO)
  1797.   while (sig && pid > (pid_t)0);   /* Hack for SCO, see earlier comment. */
  1798. #else
  1799.   while (pid > (pid_t)0);
  1800. #endif /* SCO */
  1801.  
  1802.   /* If a job was running and became stopped, then set the current
  1803.      job.  Otherwise, don't change a thing. */
  1804.   if (call_set_current)
  1805.     if (last_stopped_job != NO_JOB)
  1806.       set_current_job (last_stopped_job);
  1807.     else
  1808.       reset_current ();
  1809.  
  1810.   /* Call a SIGCHLD trap handler for each child that exits, if one is set. */
  1811.   {
  1812.     extern char *trap_list[];
  1813.  
  1814.     if ((trap_list[SIGCHLD] != (char *)DEFAULT_SIG) &&
  1815.     (trap_list[SIGCHLD] != (char *)IGNORE_SIG))
  1816.       {
  1817.     extern int last_command_exit_value;
  1818.     /* It's quite dangerous to do this from a signal handler, so
  1819.        we turn off the trap list temporarily while we parse and
  1820.        execute the command.  This will protect us against (potentially
  1821.        infinite) recursive calls.  We also preserve $? around the
  1822.        execution of trap commands, by saving and restoring the value
  1823.        of last_command_exit_value. */
  1824.  
  1825.     char *trap_command = trap_list[SIGCHLD];
  1826.     int old_exit_value = last_command_exit_value;
  1827.     trap_list[SIGCHLD] = (char *)DEFAULT_SIG;
  1828.     while (children_exited--)
  1829.       parse_and_execute (savestring (trap_command), "trap");
  1830.     trap_list[SIGCHLD] = trap_command;
  1831.     last_command_exit_value = old_exit_value;
  1832.       }
  1833.   }
  1834.  
  1835.   /* We have successfully recorded the useful information about this process
  1836.      that has just changed state.  If we notify asynchronously, and the job
  1837.      that this process belongs to is no longer running, then notify the user
  1838.      of that fact now. */
  1839.   if (asynchronous_notification && interactive)
  1840.     notify_of_job_status ();
  1841.  
  1842. #if !defined (VOID_SIGHANDLER)
  1843.   return (0);
  1844. #endif /* VOID_SIGHANDLER */
  1845. }
  1846.  
  1847. /* Function to call when you want to notify people of changes
  1848.    in job status.  This prints out all jobs which are pending
  1849.    notification to stderr, and marks those printed as already
  1850.    notified, thus making them candidates for cleanup. */
  1851. static void
  1852. notify_of_job_status ()
  1853. {
  1854.   register int job, termsig;
  1855.   char *dir = job_working_directory ();
  1856.   sigset_t set, oset;
  1857.  
  1858.   sigemptyset (&set);
  1859.   sigaddset (&set, SIGCHLD);
  1860.   sigaddset (&set, SIGTTOU);
  1861.   sigemptyset (&oset);
  1862.   sigprocmask (SIG_BLOCK, &set, &oset);
  1863.  
  1864.   for (job = 0; job < job_slots; job++)
  1865.     {
  1866.       if (jobs[job] && jobs[job]->notified == 0)
  1867.     {
  1868.       WAIT s;
  1869.  
  1870.       s = jobs[job]->pipe->status;
  1871.       termsig = WTERMSIG (s);
  1872.  
  1873.       switch (JOBSTATE (job))
  1874.         {
  1875.           /* Print info on jobs that are running in the background,
  1876.          and on foreground jobs that were killed by anything
  1877.          except SIGINT. */
  1878.  
  1879.         case JDEAD:
  1880.  
  1881.           if (jobs[job]->foreground)
  1882.         {
  1883.           if (termsig && WIFSIGNALED (s) && termsig != SIGINT)
  1884.             {
  1885.               fprintf (stderr, "%s", sys_siglist[termsig]);
  1886.  
  1887.               if (WIFCORED (s))
  1888.             fprintf (stderr, " (core dumped)");
  1889.  
  1890.               fprintf (stderr, "\n");
  1891.             }
  1892.         }
  1893.           else
  1894.         {
  1895.           pretty_print_job (job, 0, stderr);
  1896.           if (dir && strcmp (dir, jobs[job]->wd) != 0)
  1897.             fprintf (stderr,
  1898.                  "(wd now: %s)\n", polite_directory_format (dir));
  1899.         }
  1900.           jobs[job]->notified = 1;
  1901.           break;
  1902.  
  1903.         case JSTOPPED:
  1904.           fprintf (stderr, "\n");
  1905.           pretty_print_job (job, 0, stderr);
  1906.           if (dir && (strcmp (dir, jobs[job]->wd) != 0))
  1907.         fprintf (stderr,
  1908.              "(wd now: %s)\n", polite_directory_format (dir));
  1909.           jobs[job]->notified = 1;
  1910.           break;
  1911.  
  1912.         case JRUNNING:
  1913.         case JMIXED:
  1914.           break;
  1915.  
  1916.         default:
  1917.           programming_error ("notify_of_job_status");
  1918.         }
  1919.     }
  1920.     }
  1921.   free (dir);
  1922.   sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
  1923. }
  1924.  
  1925. /* getpgrp () varies between systems.  Even systems that claim to be
  1926.    Posix.1 compatible lie sometimes (Ultrix, SunOS4, apollo). */
  1927. #if defined (_POSIX_VERSION) && !defined (BSD_GETPGRP)
  1928. #  define getpgid(p) getpgrp ()
  1929. #else
  1930. #  define getpgid(p) getpgrp (p)
  1931. #endif /* !_POSIX_VERSION || BSD_GETPGRP */
  1932.  
  1933. /* Initialize the job control mechanism, and set up the tty stuff. */
  1934. initialize_jobs ()
  1935. {
  1936.   shell_pgrp = getpgid (0);
  1937.  
  1938.   if (shell_pgrp == -1)
  1939.     {
  1940.       fprintf (stderr, "%s: initialize_jobs: getpgrp failed: %s\n",
  1941.            shell_name, (char *)strerror (errno));
  1942.       exit (1);
  1943.     }
  1944.  
  1945.   /* We can only have job control if we are interactive?
  1946.      I guess that makes sense. */
  1947.  
  1948.   if (!interactive)
  1949.     {
  1950.       job_control = 0;
  1951.     }
  1952.   else
  1953.     {
  1954.       /* Make sure that we are using the new line discipline. */
  1955.  
  1956.       /* Get our controlling terminal.  If job_control is set, or
  1957.      interactive is set, then this is an interactive shell no
  1958.      matter what opening /dev/tty returns.  (It sometimes says
  1959.      the wrong thing.) */
  1960. #if !defined (SCO)
  1961.       /* SCO Unix fails attempting job control on /dev/tty. */
  1962.       if ((shell_tty = open ("/dev/tty", O_RDWR, 0666)) < 0)
  1963. #endif /* !SCO */
  1964.     shell_tty = dup (fileno (stdin));
  1965.  
  1966.       /* Find the highest unused file descriptor we can. */
  1967.       {
  1968.     int ignore, nds = getdtablesize ();
  1969.  
  1970.     while (--nds > 3)
  1971.       {
  1972.         if (fcntl (nds, F_GETFD, &ignore) == -1)
  1973.           break;
  1974.       }
  1975.  
  1976.     if (shell_tty != nds && (dup2 (shell_tty, nds) != -1))
  1977.       {
  1978.         if (shell_tty != fileno (stdin))
  1979.           close (shell_tty);
  1980.         shell_tty = nds;
  1981.       }
  1982.       }
  1983.  
  1984. #if defined (NeXT)
  1985.       /* Compensate for a bug in the NeXT 2.0 /usr/etc/rlogind. */
  1986.       if (shell_pgrp == 0)
  1987.     {
  1988.       shell_pgrp = getpid ();
  1989.       setpgid (0, shell_pgrp);
  1990.       tcsetpgrp (shell_tty, shell_pgrp);
  1991.     }
  1992. #endif /* NeXT */
  1993.  
  1994.       while ((terminal_pgrp = tcgetpgrp (shell_tty)) != -1)
  1995.     {
  1996.       if (shell_pgrp != terminal_pgrp)
  1997.         {
  1998.           SigHandler *old_ttin = (SigHandler *)signal (SIGTTIN, SIG_DFL);
  1999.           kill (0, SIGTTIN);
  2000.           signal (SIGTTIN, old_ttin);
  2001.           continue;
  2002.         }
  2003.       break;
  2004.     }
  2005.  
  2006.       if (set_new_line_discipline (shell_tty) < 0)
  2007.     {
  2008.       fprintf (stderr, "%s: initialize_jobs: line discipline: %s",
  2009.            shell_name, (char *)strerror (errno));
  2010.       job_control = 0;
  2011.     }
  2012.       else
  2013.     {
  2014.       original_pgrp = shell_pgrp;
  2015.       shell_pgrp = getpid ();
  2016.  
  2017.       if ((original_pgrp != shell_pgrp) &&
  2018.           (setpgid (0, shell_pgrp) < 0))
  2019.         {
  2020.           fprintf (stderr, "%s: initialize_jobs: setpgid: %s\n",
  2021.                shell_name, (char *)strerror (errno));
  2022.  
  2023.           shell_pgrp = original_pgrp;
  2024.         }
  2025.  
  2026.       job_control = 1;
  2027.       give_terminal_to (shell_pgrp);
  2028.     }
  2029.     }
  2030.  
  2031.   if (shell_tty != fileno (stdin))
  2032.     SET_CLOSE_ON_EXEC (shell_tty);
  2033.  
  2034. #if !defined (_POSIX_VERSION)
  2035.   signal (SIGCHLD, flush_child);
  2036. #else
  2037.   /* Some Posix job control implementations (like SCO 3.2.x) set signals to
  2038.      call sigaction with NOCLDSTOP set in sa_flags.  Make sure we get
  2039.      signalled on child status changes by using sigaction instead of
  2040.      signal. */
  2041.   {
  2042.     struct sigaction act;
  2043.     act.sa_handler = flush_child;
  2044.     sigemptyset (&act.sa_mask);
  2045.     sigaddset (&act.sa_mask, SIGCHLD);
  2046.     act.sa_flags = 0;
  2047.     sigaction (SIGCHLD, &act, (struct sigaction *)NULL);
  2048.   }
  2049. #endif /* _POSIX_VERSION */
  2050.  
  2051.   change_flag_char ('m', job_control ? '-' : '+');
  2052.  
  2053.   if (interactive)
  2054.     get_tty_state ();
  2055. }
  2056.  
  2057. /* Set the line discipline to the best this system has to offer.
  2058.    Return -1 if this is not possible. */
  2059. static int
  2060. set_new_line_discipline (tty)
  2061.      int tty;
  2062. {
  2063. #if defined (NEW_TTY_DRIVER)
  2064.   int ldisc;
  2065.  
  2066.   if (ioctl (tty, TIOCGETD, &ldisc) < 0)
  2067.     return (-1);
  2068.  
  2069.   if (ldisc != NTTYDISC)
  2070.     {
  2071.       ldisc = NTTYDISC;
  2072.  
  2073.       if (ioctl (tty, TIOCSETD, &ldisc) < 0)
  2074.     return (-1);
  2075.     }
  2076.   return (0);
  2077. #endif /* NEW_TTY_DRIVER */
  2078.  
  2079. #if defined (TERMIO_TTY_DRIVER)
  2080. #  if defined (NTTYDISC)
  2081.   if (ioctl (tty, TCGETA, &shell_tty_info) < 0)
  2082.     return (-1);
  2083.  
  2084.   if (shell_tty_info.c_line != NTTYDISC)
  2085.     {
  2086.       shell_tty_info.c_line = NTTYDISC;
  2087.       if (ioctl (tty, TCSETAW, &shell_tty_info) < 0)
  2088.     return (-1);
  2089.     }
  2090. #  endif /* NTTYDISC */
  2091.   return (0);
  2092. #endif /* TERMIO_TTY_DRIVER */
  2093.  
  2094. #if defined (TERMIOS_TTY_DRIVER)
  2095. #if defined (Ultrix) || defined (SunOS4) || defined (aixpc)
  2096.   if (tcgetattr (tty, &shell_tty_info) < 0)
  2097.     return (-1);
  2098.  
  2099.   if (shell_tty_info.c_line != NTTYDISC)
  2100.     {
  2101.       shell_tty_info.c_line = NTTYDISC;
  2102.       if (tcsetattr (tty, TCSADRAIN, &shell_tty_info) < 0)
  2103.     return (-1);
  2104.     }
  2105. #endif /* Ultrix || SunOS4 || aixpc */
  2106.   return (0);
  2107. #endif /* TERMIOS_TTY_DRIVER */
  2108.  
  2109. #if !defined (NEW_TTY_DRIVER) && !defined (TERMIO_TTY_DRIVER) && !defined (TERMIOS_TTY_DRIVER)
  2110.   return (-1);
  2111. #endif
  2112. }
  2113.  
  2114. /* Allow or disallow job control to take place.  Returns the old value
  2115.    of job_control. */
  2116. int
  2117. set_job_control (arg)
  2118.      int arg;
  2119. {
  2120.   int old;
  2121.  
  2122.   old = job_control;
  2123.   job_control = arg;
  2124.   return (old);
  2125. }
  2126.  
  2127. static SigHandler *old_tstp, *old_ttou, *old_ttin;
  2128. static SigHandler *old_cont = (SigHandler *)SIG_DFL;
  2129. static sighandler stop_signal_handler (), cont_signal_handler ();
  2130.  
  2131. /* Setup this shell to handle C-C, etc. */
  2132. initialize_job_signals ()
  2133. {
  2134.   sighandler sigint_sighandler ();
  2135.  
  2136.   if (interactive)
  2137.     {
  2138.       signal (SIGINT, sigint_sighandler);
  2139.       signal (SIGTSTP, SIG_IGN);
  2140.       signal (SIGTTOU, SIG_IGN);
  2141.       signal (SIGTTIN, SIG_IGN);
  2142.     }
  2143.   else if (job_control)
  2144.     {
  2145.       old_tstp = (SigHandler *)signal (SIGTSTP, stop_signal_handler);
  2146.       old_ttou = (SigHandler *)signal (SIGTTOU, stop_signal_handler);
  2147.       old_ttin = (SigHandler *)signal (SIGTTIN, stop_signal_handler);
  2148.     }
  2149.   /* Leave these things alone for non-interactive shells without job
  2150.      control. */
  2151. }
  2152.  
  2153. /* Here we handle CONT signals. */
  2154. static sighandler
  2155. cont_signal_handler (sig)
  2156.      int sig;
  2157. {
  2158.   initialize_job_signals ();
  2159.   signal (SIGCONT, old_cont);
  2160.   kill (getpid (), SIGCONT);
  2161.  
  2162. #if !defined (VOID_SIGHANDLER)
  2163.   return (0);
  2164. #endif /* VOID_SIGHANDLER */
  2165. }
  2166.  
  2167. /* Here we handle stop signals while we are running not as a login shell. */
  2168. static sighandler
  2169. stop_signal_handler (sig)
  2170.      int sig;
  2171. {
  2172.   signal (SIGTSTP, old_tstp);
  2173.   signal (SIGTTOU, old_ttou);
  2174.   signal (SIGTTIN, old_ttin);
  2175.  
  2176.   old_cont = (SigHandler *)signal (SIGCONT, cont_signal_handler);
  2177.  
  2178.   give_terminal_to (shell_pgrp);
  2179.  
  2180.   kill (getpid (), sig);
  2181.  
  2182. #if !defined (VOID_SIGHANDLER)
  2183.   return (0);
  2184. #endif /* VOID_SIGHANDLER */
  2185. }
  2186.  
  2187. /* Give the terminal to PGRP.  */
  2188. give_terminal_to (pgrp)
  2189.      pid_t pgrp;
  2190. {
  2191.   sigset_t set, oset;
  2192.  
  2193.   if (job_control)
  2194.     {
  2195.       sigemptyset (&set);
  2196.       sigaddset (&set, SIGTTOU);
  2197.       sigaddset (&set, SIGTTIN);
  2198.       sigaddset (&set, SIGTSTP);
  2199.       sigaddset (&set, SIGCHLD);
  2200.       sigemptyset (&oset);
  2201.       sigprocmask (SIG_BLOCK, &set, &oset);
  2202.  
  2203.       if (tcsetpgrp (shell_tty, pgrp) < 0)
  2204.     {
  2205.       /* Maybe we should print an error message? */
  2206.     }
  2207.       else
  2208.     terminal_pgrp = pgrp;
  2209.  
  2210.       sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
  2211.     }
  2212. }
  2213.  
  2214. /* Clear out any jobs in the job array.  This is intended to be used by
  2215.    children of the shell, who should not have any job structures as baggage
  2216.    when they start executing (forking subshells for parenthesized execution
  2217.    and functions with pipes are the two that spring to mind). */
  2218. delete_all_jobs ()
  2219. {
  2220.   if (job_slots)
  2221.     {
  2222.       register int i;
  2223.  
  2224.       current_job = previous_job = NO_JOB;
  2225.  
  2226.       for (i = 0; i < job_slots; i++)
  2227.     if (jobs[i] != (JOB *) NULL)
  2228.       delete_job (i);
  2229.  
  2230.       free ((char *)jobs);
  2231.       job_slots = 0;
  2232.     }
  2233. }
  2234.  
  2235. /* Turn off all traces of job control.  This is run by children of the shell
  2236.    which are going to do shellsy things, like wait (), etc. */
  2237. without_job_control ()
  2238. {
  2239.   stop_making_children ();
  2240.   start_pipeline ();
  2241.   delete_all_jobs ();
  2242.   set_job_control (0);
  2243. }
  2244.  
  2245. #if defined (PGRP_PIPE)
  2246. /* Read from the read end of a pipe.  This is how the process group leader
  2247.    blocks until all of the processes in a pipeline have been made. */
  2248. static void
  2249. pipe_read (pp)
  2250.      int *pp;
  2251. {
  2252.   char ch;
  2253.  
  2254.   if (pp[1] >= 0)
  2255.     {
  2256.       close (pp[1]);
  2257.       pp[1] = -1;
  2258.     }
  2259.  
  2260.   if (pp[0] >= 0)
  2261.     {
  2262.       while (read (pp[0], &ch, 1) == -1 && errno == EINTR)
  2263.     continue;
  2264.     }
  2265. }
  2266.  
  2267. /* Close the read and write ends of PP, an array of file descriptors. */
  2268. static void
  2269. pipe_close (pp)
  2270.      int *pp;
  2271. {
  2272.   if (pp[0] >= 0)
  2273.     close (pp[0]);
  2274.  
  2275.   if (pp[1] >= 0)
  2276.     close (pp[1]);
  2277.  
  2278.   pp[0] = pp[1] = -1;
  2279. }
  2280.  
  2281. /* Functional interface closes our local-to-job-control pipes. */
  2282. close_pgrp_pipe ()
  2283. {
  2284.   pipe_close (pgrp_pipe);
  2285. }
  2286.  
  2287. #endif /* PGRP_PIPE */
  2288.  
  2289. #endif /* JOB_CONTROL */
  2290.